/**
 * 
 */
package lex.proxyverfier.verifier;

import java.net.URL;
import java.util.Collections;
import java.util.Vector;

import org.lex.utils.SystemProperties;

import lex.proxyverfier.SpeedFormat;

/**
 * @author Daniel Liu
 */
public class VerifyResult implements Comparable<VerifyResult>
{
	private Vector<Result> results = null;
	private int totalSample = 0;
	private int validSample = 0;
	private long totalSpeed = 0L;

	public VerifyResult()
	{
		this.results = new Vector<Result>();
	}

	public void addResult( URL url, long speed )
	{
		this.totalSample++;
		if( -1L != speed )
		{
			this.validSample++;
			this.totalSpeed += speed;
		}
		Result r = new Result( url, speed );
		int idx = Collections.binarySearch( this.results, r );
		if( idx < 0 )
			idx = -idx - 1;
		this.results.insertElementAt( r, idx );
	}

	public void clear()
	{
		this.results.clear();
		this.totalSample = 0;
		this.validSample = 0;
		this.totalSpeed = 0L;
	}

	public int getTotalSample()
	{
		return totalSample;
	}

	public int getValidSample()
	{
		return validSample;
	}

	public long getAverageSpeed()
	{
		if( 0 == this.validSample )
			return -1L;
		return this.totalSpeed / this.validSample;
	}

	public String getDetailStatistics()
	{
		StringBuilder buf = new StringBuilder();
		String sep = SystemProperties.lineSeparator();
		for( Result r : this.results )
		{
			buf.append( r.url.toString() ).append( ": " );
			buf.append( SpeedFormat.format( r.speed ) );
			buf.append( sep );
		}
		return buf.toString();
	}

	@Override
	public String toString()
	{
		if( 0L == this.totalSample )
			return "";
		// valid sample percent
		StringBuilder buf = new StringBuilder();
		int percent = 100 * this.validSample / this.totalSample;
		buf.append( percent ).append( "% " );
		// average speed
		buf.append( SpeedFormat.format( this.getAverageSpeed() ) );
		return buf.toString();
	}

	public int compareTo( VerifyResult o )
	{
		return (int) (this.getAverageSpeed() - o.getAverageSpeed());
	}

	static class Result implements Comparable<Result>
	{
		URL url = null;
		long speed = -1L;

		Result( URL url, long speed )
		{
			this.url = url;
			this.speed = speed;
		}

		@Override
		public int compareTo( Result o )
		{
			if( this.speed == o.speed )
				return this.url.toString().compareTo( o.url.toString() );
			else
				return (int) (this.speed - o.speed);
		}
	}
}
